<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 * Manages operations related to the user data
 * information for the database. 
 *
 * @package Musashi
 * @author Daniel Torres
 */
 
// Make sure we have access to this page
defined('_JEXEC') or die ('Restricted access. Sorry');
jimport('joomla.application.component.model');



/**
 *  Defines a model that manages the incorporation of a Joomla registered
 *  user into the Musashi system
 *
 */
class MusashiModelUser extends JModel
{
    var $_musashiUser = null;      // keeps information about the current user
        
    /**
     *  Loads the user's database record
     */
    function loadMusashiUser()
    {
        // Get the current user
        $user =& JFactory::getUser();
        
        // See if we have him/her
        $query = "SELECT * FROM #__Musashi_Member WHERE userId =".$user->id;
        $this->_db->setQuery($query);
        $this->_musashiUser = $this->_db->loadObject();
    }
    
    /**
     *  Gets the current Musashi user
     */
    function getMusashiUser()
    {
        if( $this->_musashiUser == null ){
            $this->loadMusashiUser();
        }
        
        return $this->_musashiUser;
    }
    
    /**
     *  Verifies that the current user is a registered Musashi user. If its not,
     *  returns false and the caller can redirect to the appropriate registration page.
     *  The function makes sure the provided redirection url is accounted for, so
     *  we go back here once the user is registered.
     *  
     *  @param redirect     Address to redirect to, in case we need to register
     */
    function validateUser( $redirect = null )
    {
        // Make sure this is not a guest user
        $user =& JFactory::getUser();
        if( $user->guest )
        {
            return false;
        }

        // We might have already validated this user
        $session =& JFactory::getSession();
        $isUser  = $session->get('validUser', false);
        
        if( $isUser == true ){
            return true;
        }
        
        // Otherwise, validate! At this point, we need to create the model
        $userModel = new MusashiModelUser();
        $currentUser = $userModel->getMusashiUser();
        
        // The user doesn't exist. Register
        if( $currentUser == null )
        {
            // Save data
            $session->set('musashiRedirect', $redirect );            
            return false;            
        }        
        // The user does exist. Make sure this test succeeds from now on
        else
        {
            $session->set('validUser', true);
            return true;
        }
    }
    
    /**
     *  Returns the correct redirection path for unregistered users.
     */
    function getUnregisteredUserPath()
    {
        return JRoute::_('index.php?option=com_musashi&controller=user&view=user');
    }
    

    /**
     *  Adds a new user into the database
     */
    function updateUserData()
    {
      // Get all the information stored on the form
      $data = JRequest::get('post');
      
      // Get the adequate table object to store this information
      $row =& $this->getTable( 'members' );
      
      // bind the fields into our table object. This attempts to grab all <input> tags
      // in the form, and match them with the table object's members
      if(!$row->bind($data)){
         $this->setError($this->_db->getErrorMsg());
         return false;
      }
        
      // Make sure the record is valid
      if(!$row->check()){
         $this->setError($this->_db->getErrorMsg());
         return false;
      }
        
      // Store the updated information. New records are automatically created
      // if the ID is zero
      if(!$row->store()){
         $this->setError($this->_db->getErrorMsg());
         return false;            
      }
      
      // Update user data that is not stored by Musashi
      $user =& JFactory::getUser();
      $user->email = JRequest::getVar('email');     // email
      // ...
      
      $user->save();

      // Done!
      return true;
        
    }
    
}

?>